<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/4
 * Time: 11:20
 */

namespace app\common\model;

use think\Request;

class Nav extends Basemodel
{

    protected $autoWriteTimestamp = true;
//    protected $auto = ['name', 'ip'];
    protected $insert = ['status' => 1];
    protected $update = [];

    /**catetree
     * @return 前台无限导航
     */
    public function catenav($data = '')
    {
        //区分手机和pc链接
        $module = Request::instance()->module();
        $list = cache('DB_TREE_ARETYPE' . cookie('think_var') . $module);
        if (empty($list)) {
            !empty($data) ? $data : '';
            $tptc = $this->field('id,model,type,pid,link,Ename,name')->where($data)->order('sort ASC,id ASC')->select();
            $list = $this->_nav($tptc);
            cache('DB_TREE_ARETYPE' . cookie('think_var') . $module, $list);
        }
        return $list;

    }

    public function _nav($data, $pid = 0, $level = 0)
    {
        $arr = $html = null;
        $model = Request::instance()->module();
        switch ($model){
            case 'mobile':
                $model = $model;
                break;
            case 'index':
                $model=$model;
                break;
            default:
                $model ='index';
                break;
        }
        foreach ($data as $k => $v) {
            if ($v['pid'] == $pid) {
                if (!empty($v['link'])) {
                    $v['link'] = nav_link($v['link']);
                }elseif($v['model']=='index'){
                    $v['link']=Request::instance()->domain();
                } else {
                    $v['link'] = url($model.'/'.$v['model'] . '/index', ['navid' => $v['id']]);
                }

//                $v['link'] = stripos($v['link'], "http") === 0 ? $v['link'] : url( $v['model'].'/index', ['navid' => $v['id']]);
//                $v['link'] = Request::instance()->root(true).'/'.Request::instance()->module().'-about-index-navid-186.'.Request::instance()->ext();

                $v['chiid'] = $this->_nav($data, $v['id'], $level + 1);
                $arr [] = $v;
            }
        }
        return $arr;
    }

    /**
     * @return 无限分类
     */
    public function catetree($data = null, $html = '&nbsp;')
    {
        $list = cache('catetree' . cookie('think_var_admin'));
        if (empty($list)) {
            $data['lang'] = cookie('think_var_admin');
//            $data['grade'] = array('<',3);
            !empty($data) ? $this->where($data) : '';
            $tptc = $this->order('sort asc,id ASC')->select();
            $list = $this->sort($tptc, 0, 0, $html);
            cache('catetree' . cookie('think_var_admin'), $list);
        }
        return $list;
    }

    public function sort($data, $pid = 0, $level = 0, $html = '&nbsp;')
    {
        static $arr = array();
        foreach ($data as $k => $v) {
            if ($v['pid'] == $pid) {
                $v['level'] = str_repeat($html, $level*6);
                $v['jibie'] = $level+1;
                $v['link'] = stripos($v['link'], "http") === 0 ? $v['link'] : $v['model'] . '-' . $v['id'];
                $arr[] = $v;
                $this->sort($data, $v['id'], $level + 1, $html);
            }
        }
        return $arr;
    }


    public function del($id)
    {
        $uid = $this->where('id', $id)->value('pid');
        $this->where('pid', $id)->update(['pid' => $uid]);
        return $this->where('id', $id)->delete();
    }



    /**
     * 获得指定栏目下的子栏目的数组
     *
     * @access  public
     * @param   int     $id     栏目的ID
     * @param   int     $selected   当前选中栏目的ID
     * @param   boolean $re_type    返回的类型: 值为真时返回下拉列表,否则返回数组
     * @param   int     $level      限定返回的级数。为0时返回所有级数
     * @param   array   $map      查询条件
     * @return  mix
     */
    public function arctype_list($id = 0, $selected = 0, $re_type = true, $level = 0, $map = array(), $is_cache = true)
    {
        static $res = NULL;
        // $res = NULL;

        if ($res === NULL)
        {

            /*多语言*/
            if (empty($map['lang'])) {
                $where['lang'] = cookie('think_var_admin');
            }
            /*--end*/

            if (!empty($map)) {
                $where = array_merge($where, $map);
            }
            foreach ($where as $key => $val) {
                $key_tmp = 'c.'.$key;
                $where[$key_tmp] = $val;
                unset($where[$key]);
            }
            $fields = "c.*, c.id as typeid, count(s.id) as has_children, '' as children";
            $res = DB('nav')
                ->field($fields)
                ->alias('c')
                ->join('__NAV__ s','s.pid = c.id','LEFT')
                ->where($where)
                ->group('c.id')
                ->order('c.pid asc, c.sort asc, c.id')
                ->select();
        }
        if (empty($res) == true)
        {
            return $re_type ? '' : array();
        }

        $options = $this->arctype_options($id, $res); // 获得指定栏目下的子栏目的数组

        /* 截取到指定的缩减级别 */
        if ($level > 0)
        {
            if ($id == 0)
            {
                $end_level = $level;
            }
            else
            {
                $first_item = reset($options); // 获取第一个元素
                $end_level  = $first_item['level'] + $level;
            }

            /* 保留level小于end_level的部分 */
            foreach ($options AS $key => $val)
            {
                if ($val['level'] >= $end_level)
                {
                    unset($options[$key]);
                }
            }
        }

        $pre_key = 0;
        foreach ($options AS $key => $value)
        {
            $options[$key]['has_children'] = 0;
            if ($pre_key > 0)
            {
                if ($options[$pre_key]['id'] == $options[$key]['pid'])
                {
                    $options[$pre_key]['has_children'] = 1;
                }
            }
            $pre_key = $key;
        }

        if ($re_type == true)
        {
            $select = '';
            foreach ($options AS $var)
            {
                $select .= '<option value="' . $var['id'] . '" ';
                $select .= ($selected == $var['id']) ? "selected='true'" : '';
                $select .= '>';
                if ($var['level'] > 0)
                {
                    $select .= str_repeat('&nbsp;', $var['level'] * 4);
                }
                $select .= htmlspecialchars(addslashes($var['name'])) . '</option>';
            }

            return $select;
        }
        else
        {
            foreach ($options AS $key => $value)
            {
                ///$options[$key]['url'] = build_uri('article_cat', array('acid' => $value['id']), $value['cat_name']);
            }
            return $options;
        }
    }

    /**
     * 过滤和排序所有文章栏目，返回一个带有缩进级别的数组
     *
     * @access  private
     * @param   int     $id     上级栏目ID
     * @param   array   $arr        含有所有栏目的数组
     * @param   int     $level      级别
     * @return  void
     */
    public function arctype_options($spec_id, $arr)
    {
        static $cat_options = array();

        // $cat_options = array();

        if (isset($cat_options[$spec_id]))
        {
            return $cat_options[$spec_id];
        }

        if (!isset($cat_options[0]))
        {
            $level = $last_id = 0;
            $options = $id_array = $level_array = array();
            while (!empty($arr))
            {
                foreach ($arr AS $key => $value)
                {
                    $id = $value['id'];
                    if ($level == 0 && $last_id == 0)
                    {
                        if ($value['pid'] > 0)
                        {
                            break;
                        }

                        $options[$id]          = $value;
                        $options[$id]['level'] = $level;
                        $options[$id]['id']    = $id;
                        $options[$id]['name']  = $value['name'];
                        unset($arr[$key]);

                        if ($value['has_children'] == 0)
                        {
                            continue;
                        }
                        $last_id  = $id;
                        $id_array = array($id);
                        $level_array[$last_id] = ++$level;
                        continue;
                    }

                    if ($value['pid'] == $last_id)
                    {
                        $options[$id]          = $value;
                        $options[$id]['level'] = $level;
                        $options[$id]['id']    = $id;
                        $options[$id]['name']  = $value['name'];
                        unset($arr[$key]);

                        if ($value['has_children'] > 0)
                        {
                            if (end($id_array) != $last_id)
                            {
                                $id_array[] = $last_id;
                            }
                            $last_id    = $id;
                            $id_array[] = $id;
                            $level_array[$last_id] = ++$level;
                        }
                    }
                    elseif ($value['pid'] > $last_id)
                    {
                        break;
                    }
                }

                $count = count($id_array);
                if ($count > 1)
                {
                    $last_id = array_pop($id_array);
                }
                elseif ($count == 1)
                {
                    if ($last_id != end($id_array))
                    {
                        $last_id = end($id_array);
                    }
                    else
                    {
                        $level = 0;
                        $last_id = 0;
                        $id_array = array();
                        continue;
                    }
                }

                if ($last_id && isset($level_array[$last_id]))
                {
                    $level = $level_array[$last_id];
                }
                else
                {
                    $level = 0;
                    break;
                }
            }
            $cat_options[0] = $options;
        }
        else
        {
            $options = $cat_options[0];
        }

        if (!$spec_id)
        {
            return $options;
        }
        else
        {
            if (empty($options[$spec_id]))
            {
                return array();
            }

            $spec_id_level = $options[$spec_id]['level'];

            foreach ($options AS $key => $value)
            {
                if ($key != $spec_id)
                {
                    unset($options[$key]);
                }
                else
                {
                    break;
                }
            }

            $spec_id_array = array();
            foreach ($options AS $key => $value)
            {
                if (($spec_id_level == $value['level'] && $value['id'] != $spec_id) ||
                    ($spec_id_level > $value['level']))
                {
                    break;
                }
                else
                {
                    $spec_id_array[$key] = $value;
                }
            }
            $cat_options[$spec_id] = $spec_id_array;

            return $spec_id_array;
        }
    }

}